import router  from './index'
import pinia from '@/stores'
import { getToken } from '@/utils/auth'
import { useUser } from '@/stores/app'

const userStores  = useUser(pinia)
const whiteList = ['/login']

router.beforeEach(async (to,form,next) => {
    const hasToken = getToken()
    if(hasToken) {
        if(to.path === '/login') {
            next(form.path)
        } else {
            const hasUserInfo = userStores.name
            if(hasUserInfo) {
                next()
            } else {
                try {
                    await userStores.getUserInfo()
                    next()
                } catch (error) {
                    userStores.loginOut()
                    console.error(error || 'Has userInfo Error')
                    next(`/login?redirect=${to.path}`)
                }
            }
        }
    } else {
        if(whiteList.includes(to.path)) {
            next()
        } else {
            next(`/login`)
        }
    }
})